package com.chezhujie.www.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.chezhujie.www.constant.PageInfo;
import com.chezhujie.www.domain.Czjuserinfo;
import com.chezhujie.www.domain.Czjusermess;
import com.chezhujie.www.domain.Identitycard;
import com.chezhujie.www.domain.vo.userinfoMessVO;
import com.chezhujie.www.service.CzjuserinfoService;
import com.chezhujie.www.service.CzjusermessService;
import com.chezhujie.www.service.IdentitycardService;
import com.sys.core.page.Pagination;
import com.sys.core.utils.ConvertObj;
import com.sys.core.utils.Fileupload;
import com.sys.core.utils.UUIDUtils;
import com.sys.user.base.controller.BaseController;

@Controller
@RequestMapping("/userinfo")
public class CzjuserinfoAndMesController extends BaseController {

	private static final Logger log = LoggerFactory
			.getLogger(CzjuserinfoAndMesController.class);

		//显示所有用户
		@RequestMapping("list")
		public String login(HttpServletRequest request,Czjuserinfo czjuserinfo, String vip,HttpServletResponse response,
				Integer pageNo, Integer pageSize,
				ModelMap model) throws Exception {
	
		      if (pageNo == null) {
		            pageNo = PageInfo.DEFAULT_PAGENO;
		        }
		        if (pageSize == null) {
		            pageSize = PageInfo.DEFAULT_PAGESIZE;
		        }
		        Map<String,Object> map=new HashMap<String, Object>();
		        if(null != czjuserinfo.getTelephone()){
		        	map.put("telephone", czjuserinfo.getTelephone());
		        	model.addAttribute("telephone", czjuserinfo.getTelephone());
		        }
		        if(null != czjuserinfo.getCarplate()){
		        	map.put("carplate", czjuserinfo.getCarplate());
		        	model.addAttribute("carplate", czjuserinfo.getCarplate());
		        }
		        if(StringUtils.isNotBlank(vip)){
		        	map.put("vip", vip);
		        	model.addAttribute("vip", vip);
		        }
			try {
				// 查询所有的会员和非会员
//				List<Integer> vips=czjuserinfoService.selectVip();
				int vip1=czjuserinfoService.selectVip1();
				int vip2=czjuserinfoService.selectVip2();
				model.addAttribute("vip1", vip1);
				model.addAttribute("vip2", vip2);
				
				int sunUser=czjuserinfoService.getSumCount();
				model.addAttribute("sunUser", sunUser);
				//
				Pagination pagination=czjuserinfoService.getCzjuserAndMes(map,pageNo,pageSize);
				model.addAttribute("pagination", pagination);
				
			} catch (Exception e) {
				e.printStackTrace();
				log.error("error", e);
	
			}
	
			return "userinfo/list";
		}
	
		//禁止用户登陆
		@RequestMapping("prohibit")
		public String prohibit(@RequestParam(required=true) Integer userinfoid, 
				@RequestParam(required=true) String enable,
				HttpServletRequest request, HttpServletResponse response,
				ModelMap model) throws Exception {

			try {
				Czjuserinfo czjuserinfo=new Czjuserinfo();
				czjuserinfo.setId(userinfoid);
				czjuserinfo.setEnable(enable);
				czjuserinfoService.updateCzjuserinfo(czjuserinfo);
				
			} catch (Exception e) {
				e.printStackTrace();
				log.error("error", e);

			}

			return "redirect:/userinfo/list";
		}
		
		//禁止用户评论
				@RequestMapping("noComment")
				public String noComment(@RequestParam(required=true) String usermessId, @RequestParam(required=true) Integer userinfoid, 
						@RequestParam(required=true) String noComment,
						HttpServletRequest request, HttpServletResponse response,
						ModelMap model) throws Exception {

					try {
						if(StringUtils.isBlank(usermessId)){
							
							Czjusermess czjusermess=new Czjusermess();
							czjusermess.setNoComment(noComment);
							czjusermess.setUserinfoId(userinfoid);
							czjusermessService.insertUsermess(czjusermess);
							
							
						}else{
							
						
						Czjusermess czjusermess=new Czjusermess();
						czjusermess.setUsermessId(usermessId);
						czjusermess.setNoComment(noComment);
						czjusermessService.updateUsermess(czjusermess);
						}
						
					} catch (Exception e) {
						e.printStackTrace();
						log.error("error", e);

					}

					return "redirect:/userinfo/list";
				}
		
		//查看详情
				@RequestMapping("detail")
				public String detail(@RequestParam(required=true) Integer userinfoid, HttpServletRequest request, HttpServletResponse response,
						ModelMap model) throws Exception {

					try {

						Map<String, Object> map=new HashMap<String, Object>();
						
							map.put("id", userinfoid);
						userinfoMessVO messVO=czjuserinfoService.getCzjuserAndMesById(map);
						model.addAttribute("messVO", messVO);
					} catch (Exception e) {
						e.printStackTrace();
						log.error("error", e);

					}
						return "userinfo/detail";
				}

	
				/**
				 * 
				 * 方法名：auditInformation 认证身份证信息
				 * 创建人：RUI
				 * 时间：2017年8月21日-下午6:07:32 
				 * @param request
				 * @param respons
				 * @param pageNo
				 * @param pageSize
				 * @param identitycard
				 * @param model
				 * @return String
				 * @exception 
				 * @since  1.0.0
				 */
	@RequestMapping("/auditInformation")
	public String auditInformation(HttpServletRequest request,HttpServletResponse respons,
			Integer pageNo, Integer pageSize,Identitycard identitycard,
			ModelMap model){
		
	        if (pageNo == null) {
	            pageNo = 1;
	        }
	        if (pageSize == null) {
	            pageSize = 0;
	        }
	        try {
	            Map<String, Object> params = ConvertObj.toMap(identitycard);
	            Pagination pagination = identitycardService.list(pageNo.intValue(), pageSize.intValue(), params, model);
	            model.addAttribute("pagination", pagination);
	        } catch (Exception e) {
	            e.printStackTrace();
	            model.addAttribute("failed","获取认证信息列表失败!"+e.getMessage());
	        }
	        model.addAttribute("entity", identitycard);
	        return "identitycard/list";
		
	}
	
	/***
	 * 
	 * 方法名：addAuditInformation 新增或修改身份证信息页面
	 * 创建人：RUI
	 * 时间：2017年8月21日-下午6:07:55 
	 * @param identitycard
	 * @param req
	 * @param resp
	 * @param model
	 * @return String
	 * @exception 
	 * @since  1.0.0
	 */
    @RequestMapping("/addAuditInformation")
    public String addAuditInformation(Identitycard identitycard, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
    	
        if(StringUtils.isNotBlank(identitycard.getIdentitycardId())){
            identitycard = identitycardService.queryById(identitycard.getIdentitycardId());
            model.addAttribute("entity", identitycard);
        }
        return "identitycard/add";
    }
		
    /***
     * 
     * 方法名：saveAuditInformation 新增或修改身份证信息
     * 创建人：RUI
     * 时间：2017年8月21日-下午6:08:23 
     * @param identitycard
     * @param multipartFile_IdCardFace
     * @param multipartFile_IdCardReverse
     * @param req
     * @param resp
     * @param model
     * @return String
     * @exception 
     * @since  1.0.0
     */
    @RequestMapping("/saveAuditInformation")
    public String saveAuditInformation(Identitycard identitycard,
            @RequestParam(value = "fileIdCardFace", required = false) MultipartFile multipartFile_IdCardFace,
            @RequestParam(value = "fileIdCardReverse", required = false) MultipartFile multipartFile_IdCardReverse,
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

            if(StringUtils.isNotBlank(identitycard.getIdentitycardId())){
         /*       String idCardFace = identitycard.getIdCardFace();
                setIdCardFace(identitycard,multipartFile_IdCardFace,req);
                String idCardReverse = identitycard.getIdCardReverse();
                setIdCardReverse(identitycard,multipartFile_IdCardReverse,req);*/
            	identitycard.setCreateTime(new Date());
                identitycardService.update(identitycard);
             /*   Fileupload.deleteFile(req,idCardFace);
                Fileupload.deleteFile(req,idCardReverse);*/


            }else{
                identitycard.setIdentitycardId(UUIDUtils.getUUID());
                setIdCardFace(identitycard,multipartFile_IdCardFace,req);
                setIdCardReverse(identitycard,multipartFile_IdCardReverse,req);
                identitycardService.insert(identitycard);
            }
            model.addAttribute("success", "保存认证信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存认证信息失败!详情："+e.getMessage());
        }
        return "redirect:/userinfo/auditInformation";
    }
	
    
    
    private void setIdCardFace(Identitycard identitycard, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
        if((!multipartFile.isEmpty())&&multipartFile.getSize()>0){
            String basePath = req.getSession().getServletContext().getRealPath("/");
            String path = basePath+"upload/identitycard/"+identitycard.getIdentitycardId()+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            Fileupload.createDir(basePath+"upload/identitycard/");

            InputStream in = multipartFile.getInputStream();
            FileOutputStream out = new FileOutputStream(path);
            try {
                IOUtils.copy(in,out);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("上传图片失败！");
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

            String idCardFace = "/"+path.replace(basePath, "");
            identitycard.setIdCardFace(idCardFace);
        }
    }

    private void setIdCardReverse(Identitycard identitycard, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
        if((!multipartFile.isEmpty())&&multipartFile.getSize()>0){
            String basePath = req.getSession().getServletContext().getRealPath("/");
            String path = basePath+"upload/identitycard/"+identitycard.getIdentitycardId()+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            Fileupload.createDir(basePath+"upload/identitycard/");

            InputStream in = multipartFile.getInputStream();
            FileOutputStream out = new FileOutputStream(path);
            try {
                IOUtils.copy(in,out);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("上传图片失败！");
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

            String idCardReverse = "/"+path.replace(basePath, "");
            identitycard.setIdCardReverse(idCardReverse);
        }
    }
    
    
	@Resource
	private CzjuserinfoService czjuserinfoService;
	@Resource
	private CzjusermessService czjusermessService;
	@Autowired
	private IdentitycardService identitycardService;


}